package com.gitee.ixtf.vertx.internal.converter

import com.gitee.ixtf.vertx.ParameterConverter
import io.vertx.core.buffer.Buffer
import io.vertx.core.eventbus.Message
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.RoutingContext

object Body2JsonObjectParameterConverter : ParameterConverter<JsonObject?> {
  private fun convertBody(body: Any?): JsonObject =
      when (body) {
        is String -> JsonObject(body)
        is ByteArray -> JsonObject(Buffer.buffer(body))
        is Buffer -> JsonObject(body)
        is JsonObject -> body
        else -> throw RuntimeException()
      }

  override suspend fun convert(message: Message<*>) = message.body()?.let { convertBody(it) }

  override suspend fun convert(rc: RoutingContext) =
      rc.body()?.run { if (isEmpty) null else asJsonObject() }
}
